package controller;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.lang.reflect.Method;

public class BaseController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=UTF-8");//设置响应格式，内容类型和编码格式
        String requestURI = req.getRequestURI();//获取请求URI 统一资源标识符
        String[] split = requestURI.split("/");//拆分URI获取方法名
        String methodName =split[split.length-1];
        Class clazz=this.getClass();//获取当前类的字节码对象
        try {
            //通过反射获取当前类中同名 参数类型相同方法
            Method method=clazz.getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
            method.setAccessible(true);//设置权限（即使私有
            method.invoke(this,req,resp);//调用方法
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }
}
